#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <cstdlib>
void ChildWrite(int wfd)
{

    int cnt = 0;
    char c = 0;
    while (true)
    {
        // char buffer[1024];
        write(wfd, &c, 1);
        printf("cnt: %d\n", cnt++);
        // snprintf(buffer, sizeof(buffer), "I am child, pid: %d, cnt: %d ", getpid(), cnt++);
        // write(wfd, buffer, strlen(buffer));
        //  sleep(5);
        //  break;
    }
}
void FatherRead(int rfd)
{
    char buffer[1024];
    while (true)
    {
        sleep(100);
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "n : " << n << std::endl;
            std::cout << "child 退出，我也退出";
        }
        else
        {
            break;
        }
        // break;
    }
}

int main()
{
    // 匿名管道
    int fds[2] = {0};
    int n = pipe(fds);
    // fd[0] 读取 fd[1] 写入
    if (n < 0)
    {
        std::cerr << "pipe failed" << std::endl;
        return 1;
    }
    std::cout << "fds[0]: " << fds[0] << std::endl;
    std::cout << "fds[1]: " << fds[1] << std::endl;

    // 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // 子进程
        // 子进程写入
        close(fds[0]);
        ChildWrite(fds[1]); // 写入内容
        close(fds[1]);
        exit(0);
    }
    // 父进程
    // 父进程读取
    close(fds[1]);
    FatherRead(fds[0]); // 读取内容
    close(fds[0]);
    sleep(5);
    int status = 0;
    int ret = waitpid(id, &status, 0);
    if (ret > 0)
    {
        printf("exit code: %d,exit signal:%d\n", (status >> 8) & 0xff, (status) & 0x7f);
        sleep(5);
    }

    return 0;
}
